// pages/noticeDetail/noticeDetail.js
var userModel = require('../../models/user.js')
var klassModel = require('../../models/klass.js')
let noticeModel = require('../../models/notice.js')
let receiptModel = require('../../models/receipt.js')
var util = require('../../utils/util.js')
var bxt = require('../../utils/bxt.js') 
var request = require('../../operation/operation.js')
var appOptions = null // 保存app.js onLaunch传来的options值
var notice = null
var noticeSid // 分享界面获取到的sid
var klassSid = null // 要查看哪个班的签收状态 
var currentUserRole = null  // 来源是分享界面时，如果用户是同一个组，需要进行用户身份检查
let receipteds = [] // 已签收数组信息
let noreceipts = [] // 未签收数组信息
var messageContentTemplate = require('../../template/messageContent/messageContent.js')
let exportEmailModelTemplate = require('../../template/exportEmailModal/exportEmailModal.js')
let getNoticeOperation = require('../../operation/getNoticeOperation.js')
let getReceiptListOperation = require('../../operation/getReceiptListOperation.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    notice:null,
    back:false,    
    receipted:false,
    canReceipt:false,
    edit:false,
    receipts:null,
    receiptShowMode: 'receipted', // receipted 已签收 noReceipt 未签收
    disabled: false, // 确定按钮可用/不可用控制
    loading: false, // 通信加载提示
    showEmailButton: false,  // 显示发送邮件按钮；
    email: '', // 邮箱内容
    emailDesc:'', // 文字、图片功能描述
    login:false // 显示授权登录入口
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    wx.hideShareMenu()

    this.initBackButton()

    if (appOptions || options.noticeSid) {  // 获取通知详情
      noticeSid = options.noticeSid
      klassSid = options.klassSid
    }

    if (userModel.getCurrentUser()) {
      this.setData({
        login: false
      })

      if (appOptions || options.noticeSid) {

      } else if (getApp().globalData.param) { // 保存的是notice对象
        notice = getApp().globalData.param
        noticeSid = notice.sid
        klassSid = notice.klassInfo.sid
      }
      this.getNotice()
    }else {
      // 授权用户登录  
      this.setData({
        login:true
      })
    }
   
    getApp().notificationCenter.register(bxt.ACTIVATE_KCLASS_MESSAGE, this, "handleActivateKclassMessage")
    getApp().notificationCenter.register(bxt.BIND_ROLE_MESSAGE, this, "updateUser")
    getApp().notificationCenter.register(bxt.RECEIPT_SUCCESSED_MESSAGE, this, "handleReceiptMessage");
    getApp().notificationCenter.register(bxt.REVIEW_FAIL_MESSAGE, this, "handleReviewFialMessage");
    getApp().notificationCenter.register(bxt.DELETE_REVIEW_MESSAGE, this, "handleReviewFialMessage");
    getApp().notificationCenter.register(bxt.REVIEW_PASS_MESSAGE, this, "handleReviewFialMessage");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {    
    appOptions = null
    notice = null
    currentUserRole = null
    getApp().notificationCenter.remove(bxt.ACTIVATE_KCLASS_MESSAGE, this)
    getApp().notificationCenter.remove(bxt.BIND_ROLE_MESSAGE, this)
    getApp().notificationCenter.remove(bxt.RECEIPT_SUCCESSED_MESSAGE, this);
    getApp().notificationCenter.remove(bxt.REVIEW_FAIL_MESSAGE, this);
    getApp().notificationCenter.remove(bxt.REVIEW_PASS_MESSAGE, this);
    getApp().notificationCenter.remove(bxt.DELETE_REVIEW_MESSAGE, this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (userModel.getCurrentUser()) {
      this.getNotice()
    } else {
      wx.stopPullDownRefresh()
      // this.logon()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    let that = this,isBindClass = true
    for (let index = 0, length = notice.receiptStatus.length; index < length; index++) {  // 检查是否需要绑定通知和班级的关系
      if (notice.receiptStatus[index].klassSid == klassSid) {
        isBindClass = false;
        break
      }
    }

    return noticeModel.shareMessageToWeXin(this, options, notice, klassSid, isBindClass, function () {
      if (true == isBindClass) {
        that.getNotice()
      }
    })  
  },

  /**
  * 点击图片预览事件处理函数
  */
  previewImage: function (event) {
    messageContentTemplate.previewImage(event.currentTarget.dataset.path.url, receiptModel.getImagesUrl(this.data.notice.imagesArray))
  },
  
  /**
   * 签收事件处理函数
   */
  onReceipt:function(event) {

    if (userModel.getCurrentUser()) {
      if (currentUserRole.role == userModel.NORMAL) {
        this.showBindRelationModal()
        return
      }

      getApp().createFormId(event.detail.formId)
      
      getApp().globalData.param = {'notice': this.data.notice,'userRole':currentUserRole}
      
      if (1 < currentUserRole.relations.length) { // 多个孩子先进孩子选择界面
        wx.navigateTo({
          url: '../receiptStudentSelectList/receiptStudentSelectList',
        })
      }else { // 一个孩子直接进签收界面
        // if (this.data.receipted) {  // 更新
        //   getApp().globalData.param = { 'notice': this.data.notice, 'userRole': currentUserRole, 'receipt': notice.myReceipts[0] }
        //   wx.navigateTo({
        //     url: '../receiptNotice/receiptNotice?receiptSid=' + notice.myReceipts[0].sid,
        //   })
        // }else { // 创建签收
          receiptModel.createReceipt(this, this.data.notice, currentUserRole.relations[0].student.sid)
        // }
      }
    }
  },

  onHome:function() {
    if (klassModel.getCurrentAllClass() && 0 < klassModel.getCurrentAllClass().length) {
      wx.switchTab({
        url: '../noticeList/noticeList',
      })
    }else {
      wx.redirectTo({
        url: '../introduce/introduce',
      })
    }
  },

  onShowReceiptDetail:function(event) {
    var receipt = event.currentTarget.dataset.receipt    
    if (this.data.receiptShowMode == 'noReceipt') {
      return
    }else {
      if (receipt.receipt) {
        receipt = receipt.receipt
      }
      getApp().globalData.param = { 'notice': this.data.notice, 'receipt': receipt }
      wx.navigateTo({
        url: '../receiptDetail/receiptDetail',
      })
    }
  },

  /**
   * 点击切换显示签收模式列表事件处理函数
   */
  onSwitchShowMode:function(event) {
    this.setData({
      receiptShowMode:event.currentTarget.dataset.mode
    })

    this.refreshReceiptListView()
  },

  /**
   * 点击班级签收情况事件处理函数
   */
  onShowReceiptList: function (event) {
    let notice = this.data.notice
    notice.klass = event.currentTarget.dataset.klass // 为了下个界面获取到班级信息
    notice.klass.sid = notice.klass.klassSid

    getApp().globalData.param = { 'notice': notice }

    wx.navigateTo({
      url: '../receiptList/receiptList?noticeSid=' + this.data.notice.sid,
    })
  },

  bindGetUserInfo: function (event) {
      var that = this
      getApp().getUserInfo(event.detail,function (wxUserInfo, userInfo, message) {
        if (wxUserInfo != null) {
          that.getNotice()
        } else {
          wx.showModal({
            title: '提示',
            content: message,
            showCancel: false
          })
        }
      })
    
  },

  /**
   * 获取通知详情
   */
  getNotice:function() {
    this.setData({
      login: false
    })
    
    var that = this; 

    getNoticeOperation.getNotice(noticeSid, klassSid)
      .then(res => {
        notice = res          
        notice.klass = klassModel.getKlassUIData(notice.klass)        
        that.initNoticeView()
        that.handleCheck()
        exportEmailModelTemplate.init(that, notice)        
        that.checkEmailButton() 
      })
      .catch(res => {
        wx.showModal({
          title: '提示',
          content: '通知已被删除',
          showCancel: false,        
          confirmText: '返回首页',          
          success: function(res) {
            that.onHome()
          }          
        })
      })

    // getReceiptListOperation.getReceiptList(noticeSid, klassSid) 
    //   .then(res => {
    //     that.initReceiptListView(res)
    //     that.refreshReceiptListView()
    //   })
  },

  /**
   * 更新用户信息
   * 绑定身份成功后，需要更新用户信息
   */
  updateUser:function() {
    var that = this

    if (getApp().globalData.userInfo) {
      getApp().updateUserInfo(function (userInfo) {
        if (userInfo) {
          that.refreshGroupView()
        }
      })
    } 
  },

  /**
   * 接收签收消息，刷新界面显示
   */
  handleReceiptMessage:function(object) {
    notice = getApp().globalData.param.notice
    this.refreshGroupView()
    this.initNoticeView()

    // 将noreceipts数据移到noreceipts
    let receipt;
    for (let index = 0, length = noreceipts.length; index < length; index++) {
      if (noreceipts[index].sid == object.receiptObject.student.sid) {
        receipt = noreceipts[index]
        receipt.receipt = object.receiptObject
        receipt.receipt.pointCount = object.receiptObject.point.count
        receipteds.push(receipt)
        noreceipts.splice(index,1)
        break
      }
    }

    this.refreshReceiptListView()
  },

  handleActivateKclassMessage:function() {
    this.refreshGroupView()
    // 激活班级后需要把这个通知与班级进行绑定
    // let shareTickets = [appOptions.shareTicket]
    // getApp().bindNoticeToClass(shareTickets, notice.sid, klassSid, function () {

    // })
  }, 

  handleReviewFialMessage: function (object) {
    notice.receiptStatus[0].currentStatus = object.notice.receiptStatus[0].currentStatus
    this.initNoticeView()
  },

  /**
   * 检查流程
   * 检查班级是否激活、检查是否绑定了角色
   */
  handleCheck:function() {
    this.refreshGroupView()    
    console.log(appOptions)
    if (null != appOptions && false == this.checkActivateClass()) { // 未激活先对班级进行激活操作
      if (notice.category && 101 == notice.category) {  // category 101 代表激活类型的通知
        getApp().globalData.param = { 'appOptions': appOptions, 'notice': notice }
        wx.navigateTo({
          url: '../activateClass/activateClass',
        })
      }   
    } else if (null != appOptions && true == this.checkActivateClass()) { // 如果班级与群绑定过，就检查班级与来源群的关系
      console.log('11')
      this.checkGroupKclass()
    }
  },

  /**
   * 控制编辑/签收按钮的显示
   */
  refreshGroupView:function () {
    currentUserRole = userModel.getRole(notice.klass)
    this.initReceiptButton()
  },

  /**
   * 检查通知来源群和班级的关系
   * 如果用户在当前班级有身份，就有签收权利，无论来源群是否和班级绑定过
   */
  checkGroupKclass:function() {
    let that = this
    wx.getShareInfo({
      shareTicket: appOptions.shareTicket,
      success(res) {
        request.postRequest('/check-klass', { 'encryptedData': res.encryptedData, 'iv': res.iv, 'klassSid': klassSid}, true)
          .then(res => {
            let data = res.data, canReceipt = false;
            if (request.SUCCESSED == data.status) { // 同班级同群,需要绑定
              canReceipt = true
              if (currentUserRole.role == userModel.NORMAL) {            
                that.showBindRelationModal()
              }
            }else {
              if (currentUserRole.role == userModel.PATRIARCH) {
                canReceipt = true
              }else {
                that.setData({
                  receipted: false,
                  canReceipt: false
                })

                if (currentUserRole.role == userModel.NORMAL) { 
                  wx.showModal({
                    title: '提示',
                    content: '您不在此班级微信群中，只能查看此通知',
                    showCancel: false
                  })
                }
              }              
            }

            if (canReceipt) {              
              that.initReceiptButton()
            }
          }).catch(e => {
            console.log(e)
          })
      },
      fail(res) {
        that.setData({
          receipted: false,
          canReceipt: false
        })
      }
    })
  },

  /**
   * 初始化通知信息视图
   */
  initNoticeView:function() {
    messageContentTemplate.initMessageContentView(this, notice,false)
    if (notice.receiptStatus && 0 < notice.receiptStatus.length) {
      let receiptStatus = notice.receiptStatus[0].currentStatus.split('/');
      notice.receipt = receiptStatus[0];
      notice.noReceipt = receiptStatus[1] - receiptStatus[0];
    }
    
    this.setData({
      notice:notice
    })

    if (noticeModel.RECEIPT_REQUIREMENT[0].value != notice.receiptRequirement) {
      this.setData({
        receiptButtonDesc: noticeModel.getReceiptRequirement(notice.receiptRequirement).name
      })
    }else {
      this.setData({
        receiptButtonDesc:''
      })
    }
  },

  /**
   * 检查是否需要显示激活班级界面
   * return false 表示没有激活班级，需要激活
   */
  checkActivateClass:function() {
    var result = true
    if (null == notice.klass || !notice.klass.wxGroupUid) {
      result = false
      return result
    }
    
    return result
  },

  /**
   * 初始化返回按钮是否显示逻辑函数
   */
  initBackButton: function () {
    if (getApp().globalData.param.appOptions) {  // 场景来自小卡片
      appOptions = getApp().globalData.param.appOptions  // 如果来源小卡片，将参数保留下来
      this.setData({
        back: true
      })
    }
  },

  /**
   * 初始化签收按钮状态
   */
  initReceiptButton:function() {
    var user = userModel.getCurrentUser()
    if (user) {
      if (currentUserRole.role == userModel.HEAD_TEACHER || currentUserRole.role == userModel.TEACHER) { // 老师身份不用签收
        this.setData({
          canReceipt:false
        })
      } else if (currentUserRole.role == userModel.NORMAL) {
        this.setData({
          receipted:false,
          canReceipt: true
        })
      }else {
        if (currentUserRole.relations) {
          let receipted = false
          if (notice.myReceipts && notice.myReceipts.length == currentUserRole.relations.length) { // 如果签收数量等于当前学生数量，认为签收完毕
            receipted = true
          }

          this.setData({
            receipted: receipted,
            canReceipt: true
          })
        }
       
      }
    }
  },

  refreshNoticeView:function() {
    notice = getApp().globalData.param
    this.initNoticeView()
  },

  showBindRelationModal:function() {
    wx.showModal({
      title: '绑定关系',
      content: '您还没有绑定您在班级的关系，请绑定关系',
      confirmText: '绑定关系',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../selectRole/selectRole?klassSid=' + notice.klass.sid,
          })
        }
      }
    })
  },

  /**
   * 
   */
  initReceiptListView: function (receipts) {
    receipteds = [], noreceipts = []

    for (let index = 0, length = receipts.length; index < length; index++) {
      if (receipts[index].receipt) {
        receipteds.push(receipts[index])
      } else {
        noreceipts.push(receipts[index])
      }
    }
  },
  /**
   * 根据不同的签收浏览模式，绑定不同的数据
   */
  refreshReceiptListView:function() {
    if (this.data.receiptShowMode == 'noReceipt') {
      this.setData({
        receipts:noreceipts
      })
    }else {
      this.setData({
        receipts: receipteds
      })
    }
  },

  /**
* 设置按钮状态
*/
  setButtonLoading: function (loading) {
    this.setData({
      disabled: loading,
      loading: loading
    })
  },

  /**
   * 邮箱输入框输入事件处理函数
   */
  bindKeyInput: function (event) {
    exportEmailModelTemplate.setEmail(event.detail.value)
  },

  /**
     * 检查是否显示导出到邮箱按钮
     * 通知签收类型是文字、图片，并且当前用户是班主任或者通知创建者显示此按钮
     */
  checkEmailButton: function () {  
    let showEmailButton = false
    if (notice.receiptRequirement == 'text' || notice.receiptRequirement == 'image') {
      if ((userModel.HEAD_TEACHER == userModel.getRole(notice.klass).role || notice.creatorSid == userModel.getCurrentUser().sid) && notice.receipt != '0') {
        showEmailButton = true       
      }
    }

    this.setData({
      showEmailButton: showEmailButton
    })
  },

  /**
    * 显示输入邮箱对话框
    */
  showInputEmailDialog: function () {
    exportEmailModelTemplate.show(notice.klass.sid)
  },

  /**
   * 输入邮箱对话框取消按钮事件
   */
  onCancel() {
    exportEmailModelTemplate.cancel()
  },

  onConfirm(event) {
    exportEmailModelTemplate.confirm()
  }
})